package com.ftg.learn.loadbalance;

import java.util.Arrays;
import java.util.List;

/**
 * @author 布衣
 */
public class MinConnectionQuery {

    private volatile int currentNode = 0;

    public synchronized RedisInstance get(List<RedisInstance> list, int index) {
        RedisInstance redisInstance = list.get(currentNode);
        if (redisInstance.getActiveConnections().intValue() == redisInstance.getMinConnections().intValue()) {
            currentNode++;
            if (currentNode == list.size()) {
                currentNode = 0;
            }
            redisInstance.setActiveConnections(0);
            list.get(currentNode).setActiveConnections(list.get(currentNode).getActiveConnections() + 1);
            return list.get(currentNode);
        } else {
            redisInstance.setActiveConnections(redisInstance.getActiveConnections() + 1);
        }
        return redisInstance;
    }

    public static void main(String[] args) {
        MinConnectionQuery t = new MinConnectionQuery();
        List<RedisInstance> list = Arrays.asList(
                new RedisInstance("127.0.0.1",6380,4),
                new RedisInstance("127.0.0.1",6381,6),
                new RedisInstance("127.0.0.1",6382,3)
        );
        for (int i = 0; i < 100; i++) {
            System.out.println(t.get(list, i)+"===>"+i);
        }
    }

}
